package com.sumer.psychology.common.resource;

import com.sumer.psychology.common.application.ApplicationServiceRegistry;
import com.sumer.psychology.common.domain.model.Author;
import com.sumer.psychology.common.domain.model.Role;
import com.sumer.psychology.common.domain.model.User;
import com.sumer.psychology.common.port.adapter.service.AuthorCommand;
import org.apache.commons.lang3.StringUtils;

import javax.ws.rs.core.*;
import java.util.Collections;
import java.util.Map;

/**
 * Rest资源基类
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/12
 * Time: 14:44
 */
public abstract class AbstractResource {
    @Context
    protected HttpHeaders httpHeaders;

    protected CacheControl cacheControlFor(int aNumberOfSeconds) {
        CacheControl cacheControl = new CacheControl();
        cacheControl.setMaxAge(aNumberOfSeconds);
        return cacheControl;
    }

    /**
     * 当前用户ID
     *
     * @return user id
     */
    protected String currentUserId() {
        Map<String, Cookie> cookies = httpHeaders.getCookies();
        Cookie uId = cookies.get("uid");
        Cookie uIdPk = cookies.get("uidpk");

        if (uId == null || uIdPk == null || StringUtils.isAnyBlank(uId.getValue(), uIdPk.getValue())) {
            throw new LoginException();
        }

        String userId = ApplicationServiceRegistry
                .userService()
                .userId(uId.getValue(), uIdPk.getValue());

        if (StringUtils.isBlank(userId)) {
            throw new LoginException();
        }

        return userId;
    }

    private void checkRole(String userId) {
        User currentUser = ApplicationServiceRegistry
                .userService()
                .userFrom(userId);

        if (currentUser.role() == Role.AGENT) {
            throw new RoleException(currentUser.role());
        }
    }

    /**
     * 设置author
     *
     * @param authorCommand author command
     */
    protected void checkAuthorAndRole(AuthorCommand authorCommand) {
        String currentUserId = currentUserId();
        checkRole(currentUserId);

        if (authorCommand.author() == null || StringUtils.isBlank(authorCommand.author().identity())) {
            authorCommand.setAuthor(new Author(currentUserId));
        }
    }

    protected Response response(Object target) {
        return Response.ok(target).build();
    }

    protected Map<String, String> savedId(String id) {
        return Collections.singletonMap("_id", id);
    }
}
